import { downloadBlob, http } from '@/utils/http'
import type { AxiosResponseHeaders } from 'axios'

/**
 * 获取文件 blob 数据
 * @param params
 * @returns
 */
export const downloadFileRaw = (params: { filePath: string; fileName: string }) => {
  if (!params.filePath || !params.fileName) {
    return Promise.reject()
  }
  return http
    .get<{}, { data: Blob; headers: AxiosResponseHeaders }>(
      params.filePath,
      {
        responseType: 'blob',
      },
      { params }
    )
    .then(({ data }) => data)
}

/**
 * 下载单个文件
 * @param params
 * @returns
 */
export const downloadFile = (params: { filePath: string; fileName: string }) => {
  if (!params.filePath || !params.fileName) {
    return Promise.reject()
  }
  return http
    .get<{}, { data: Blob; headers: AxiosResponseHeaders }>(
      params.filePath,
      {
        responseType: 'blob',
      },
      { params }
    )
    .then((res) => {
      const { data } = res
      // const encodedFilename = headers.get('download-filename')?.toString()
      // const filename = decodeURIComponent(encodedFilename)
      downloadBlob(data, params.fileName)
    })
}

/**
 * 获取文件的blob
 * @param params
 * @returns
 */
export const getLibraryFileBlob = (params?: object, signal?: AbortSignal) => {
  return http.get<{}, { data: Blob; headers: AxiosResponseHeaders }>(
    '/pm/libraryFile/download',
    {
      responseType: 'blob',
    },
    { params, signal }
  )
}

/** 可预览的文件类型 */
export const previewTypeArr = ['docx', 'xlsx', 'pdf', 'jpg', 'png', 'jpeg', 'gif', 'bmp']
